const md5 = require('md5');
const JWT = require('jsonwebtoken');
const fs = require('fs');
const cuid = require('cuid');
const config = require('../config.js');

module.exports = {
  /**
   * 设置用户权限
  */
  async setGroup(req, { boom }) {
    const { id } = req.params;
    const { group } = req.payload;
    // 判断组是否存在
    const gps = await req.policiesModel.getGroups();
    const len = [...new Set([...gps, ...group])].length;
    if (len > gps.length) {
      return boom.badRequest('组不存在');
    }
    await req.usersModel.setGroup(id, group);
    return {};
  },
  /**
   * 修改当前登陆用户密码
  */
  async editPassword(req, { boom }) {
    const {
      newPassword,
      oldPassword,
    } = req.payload;
    const result = await req.usersModel.editPassword(
      req.auth.credentials.uid,
      md5(oldPassword),
      md5(newPassword),
    );
    if (!result) {
      return boom.badRequest('原来密码错误');
    }

    return {};
  },
  /**
   * 更新用户头像
  */
  async editAvatar(req) {
    const { file: { path, filename } } = req.payload;
    const ext = filename.split('.');
    const fname = `${cuid()}.${ext.pop()}`;
    const newPath = `./public/uploads/${fname}`;
    fs.renameSync(path, newPath);
    const { avatar } = await req.usersModel.editAvatar(req.auth.credentials.uid, { avatar: fname });
    // 删除原来的图片
    const oldPath = `./public/uploads/${avatar}`;
    if (!fs.existsSync(oldPath)) {
      return {};
    }
    fs.access(oldPath, fs.constants.F_OK, (err) => {
      if (!err) {
        fs.unlinkSync(oldPath);
      }
    });
    return {};
  },
  /**
   * 用户登陆
  */
  async login(req, { boom }) {
    const { username, password } = req.payload;
    const result = await req.usersModel.login(username, md5(password));
    if (!result) {
      return boom.badRequest('登陆失败');
    }
    const { _id: uid, group } = result;
    return JWT.sign({
      uid,
      username,
      group,
      exp: Math.floor(new Date().getTime() / 1000) + 7 * 24 * 60 * 60,
    }, 'curd');
  },
  /**
   * 获取用户
  */
  async getUsers(req) {
    const { searchField, searchValue } = req.query;
    let countParams = {};
    if (searchField && searchValue) {
      countParams = {
        searchField,
        searchValue,
      };
    }
    const count = await req.usersModel.getUsersCount(countParams);

    const result = await req.usersModel.getUsers(req.query);

    result.forEach((el, index) => {
      result[index].avatar = el.avatar === '' ? '' : `${config.imgUrl}/${el.avatar}`;
    });
    return {
      count,
      result,
    };
  },
  /**
   * 添加
  */
  async addUser(req, { boom }) {
    const {
      username,
      email,
      phone,
    } = req.payload;
    const usernameExist = await req.usersModel.isExist('username', username);
    if (usernameExist) {
      return boom.badRequest('用户名已存在');
    }
    const emailExist = await req.usersModel.isExist('email', email);
    if (emailExist) {
      return boom.badRequest('邮箱已存在');
    }
    const phoneExist = await req.usersModel.isExist('phone', phone);
    if (phoneExist) {
      return boom.badRequest('手机已存在');
    }

    const result = await req.usersModel.addUsers(req.payload);
    result.avatar = result.avatar === '' ? '' : `${config.imgUrl}/${result.avatar}`;
    return result;
  },

  /**
   * 根据ID获取单个用户信息
   */
  async getUserById(req) {
    const result = await req.usersModel.getUserById(req.params.id);
    result.avatar = result.avatar === '' ? '' : `${config.imgUrl}/${result.avatar}`;
    return result;
  },
  /*
    获取登陆用户信息
  */
  async getUserLogined(req) {
    const result = await req.usersModel.getUserById(req.auth.credentials.uid);
    result.avatar = result.avatar === '' ? '' : `${config.imgUrl}/${result.avatar}`;
    return result;
  },

  /**
   * 根据ID删除用户
   */
  async deleteUserById(req) {
    await req.usersModel.deleteUserById(req.params.id);
    return {};
  },
  /**
   * 根据多个ID批量删除用户
  */
  async deleteUsersByIds(req) {
    await req.usersModel.deleteUsersByIds(req.payload.ids);
    return {};
  },

  /**
   * 根据ID更新用户信息
  */
  async updateUserById(req, { boom }) {
    const {
      username,
      email,
      phone,
    } = req.payload;

    const user = await req.usersModel.getUserById(req.params.id);

    if (user.username !== username) {
      const usernameExist = await req.usersModel.isExist('username', username);

      if (usernameExist) {
        return boom.badRequest('用户名已存在');
      }
    }

    if (user.email !== email) {
      const emailExist = await req.usersModel.isExist('email', email);
      if (emailExist) {
        return boom.badRequest('邮箱已存在');
      }
    }
    if (user.phone !== phone) {
      const phoneExist = await req.usersModel.isExist('phone', phone);
      if (phoneExist) {
        return boom.badRequest('手机已存在');
      }
    }
    await req.usersModel.updateUserById(req.params.id, req.payload);
    return {};
  },
  /**
   * 编辑登陆用户信息
  */
  async updateUserLogined(req, { boom }) {
    const {
      username,
      email,
      phone,
    } = req.payload;

    const user = await req.usersModel.getUserById(req.auth.credentials.uid);

    if (user.username !== username) {
      const usernameExist = await req.usersModel.isExist('username', username);
      if (usernameExist) {
        return boom.badRequest('用户名已存在');
      }
    }

    if (user.email !== email) {
      const emailExist = await req.usersModel.isExist('email', email);
      if (emailExist) {
        return boom.badRequest('邮箱已存在');
      }
    }

    if (user.phone !== phone) {
      const phoneExist = await req.usersModel.isExist('phone', phone);
      if (phoneExist) {
        return boom.badRequest('手机已存在');
      }
    }
    await req.usersModel.updateUserById(req.auth.credentials.uid, req.payload);
    return {};
  },
  /**
   * 判断字段值是否存在
  */
  async isExist(req) {
    const { field, value } = req.query;
    const result = await req.usersModel.isExist(field, value);
    return Boolean(result);
  },
};
